import type { Router } from 'vue-router'
import { registerAsyncRoutes } from '../router/modules/dynamicRoutes'
import { useMenuStore } from '../stores/menu'

export default {
  install(app: any, { router }: { router: Router }) {
    console.log('路由恢复插件已加载')
    
    // 在应用挂载前恢复路由
    const isLoggedIn = !!localStorage.getItem('accessToken')
    const shouldRecoverRoutes = isLoggedIn && localStorage.getItem('dynamic_route_added') === 'true'
    
    if (shouldRecoverRoutes) {
      try {
        console.log('启动阶段: 检测到用户已登录，尝试恢复动态路由')
        
        // 直接从localStorage恢复路由，不依赖Pinia
        const menuData = localStorage.getItem('user_menu_data')
        if (menuData) {
          const parsedMenuList = JSON.parse(menuData)
          const visibleMenuList = parsedMenuList.filter((item: any) => !item.hidden)
          
          // 输出菜单项数量
          console.log(`找到 ${visibleMenuList.length} 个菜单项，准备恢复路由`)
          
          // 立即注册路由，确保路由在Vue Router初始化前就已准备好
          registerAsyncRoutes(router, visibleMenuList)
          
          // 打印已注册的路由
          console.log('已恢复的路由:', router.getRoutes().map(r => ({ 
            path: r.path, 
            name: r.name ? String(r.name) : 'null' 
          })))
          
          // 如果Pinia已经可用，同步更新store状态
          try {
            const menuStore = useMenuStore()
            menuStore.setDynamicRouteAdded(true)
            console.log('Pinia状态已同步更新')
          } catch (err) {
            console.log('Pinia尚未准备好，跳过状态更新')
          }
          
          console.log('路由恢复完成 (应用初始化阶段)')
        } else {
          console.warn('本地无缓存菜单数据，无法恢复路由')
        }
      } catch (error) {
        console.error('初始化阶段路由恢复失败:', error)
      }
    } else {
      console.log('用户未登录或无路由缓存，跳过路由恢复')
    }
    
    // 添加全局mixins或方法
    app.config.globalProperties.$recoverRoutes = async () => {
      try {
        const menuStore = useMenuStore()
        const response = await menuStore.getUserMenu(false) // 不强制刷新
        
        if (response.success && response.data) {
          registerAsyncRoutes(router, menuStore.dynamicMenuList)
          menuStore.setDynamicRouteAdded(true)
          return true
        }
      } catch (err) {
        console.error('手动恢复路由失败:', err)
      }
      return false
    }
  }
}